package com.weme.message

import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseSingleItemAdapter
import com.chad.library.adapter.base.QuickAdapterHelper
import com.chad.library.adapter.base.util.setOnDebouncedItemClick
import com.chad.library.adapter.base.viewholder.QuickViewHolder
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.jeremyliao.liveeventbus.LiveEventBus
import com.makeramen.roundedimageview.RoundedImageView
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.weme.common.arouter.ARouterHelper
import com.weme.common.arouter.ARouterPaths
import com.weme.common.base.BaseFragment
import com.weme.common.util.*
import com.weme.common.view.BottomSelectionDialog
import com.weme.common.view.BottomSelectionListener
import com.weme.common.view.SelectionItem
import com.weme.common.view.SmoothImageView
import com.weme.message.bean.MseeageBean
import com.weme.message.databinding.FragmentMessageBinding
import com.weme.message.ext.CustomAnimation1
import com.weme.message.ext.getMessageContent
import com.weme.message.viewmode.MessageViewMode
import dev.kratos.api.user_server.v1.GetUserInfoReply
import dev.kratos.api.user_server.v1.GetUserInfoRequest
import dev.kratos.api.user_server.v1.Users
import io.agora.CallBack
import io.agora.ValueCallBack
import io.agora.chat.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

@Route(path = ARouterPaths.MESSAGEFRAGMENT)
class MessageFragment : BaseFragment<FragmentMessageBinding, MessageViewMode>(), BottomSelectionListener {

    private var pageNum = 1
    var messageAdapterList: ArrayList<MseeageBean> = ArrayList()
    override fun startOperate() {
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).titleBar(mBinding.calView).init()
        UserMKHelper.encode(UserMKHelper.OPEN_APP, true)
        observeViewModel()
        initAdapter()
     LiveEventBus.get<Any>(LiveConfig.NET_WORK_MESSAGE).observe(this) {
            if (it is GetUserInfoReply) {
                handleGetUserInfoResponse(it)
            }
        }
     LiveEventBus.get<Any>(LiveConfig.NET_WORK_MESSAGE_ADD).observe(this) {
            if (it is GetUserInfoReply) {
                handleAddUserInfoResponse(it)
            }
        }
    }


    private fun handleGetUserInfoResponse(getUserInfoReply: GetUserInfoReply) {
        callAdapter.isStateViewEnable = true
        val sortedConversations = AgoraClient.getInstance().getMessageList().values.toList().sortedByDescending { it.lastMessage.msgTime } //服务器拿到的数据 转成map
        Log.e("message","声网拿到的数据"+ sortedConversations.size)
        val usersMap = getUserInfoReply.usersList.associateBy { it.uid.toString() }
        val mseeageList = sortedConversations.mapNotNull { conversation ->
            usersMap[conversation.conversationId()]?.let { users ->
                val content = getMessageContent(conversation.lastMessage)
                MseeageBean(users = users, content = content, time = conversation.lastMessage.msgTime, newCount = conversation.unreadMsgCount, conversationId = conversation.conversationId())
            }
        }

        updateMessageList(mseeageList, usersMap)

    }
    //收到新消息
    private fun handleAddUserInfoResponse(getUserInfoReply: GetUserInfoReply) {

        val getUserInfoItem = getUserInfoReply.usersList.get(0)
        val content = getMessageContent(addChatMessage!!)

        val chat = addChatMessage?.conversationId()?.let { conversationId ->
            addChatMessage?.msgTime?.let { msgTime ->
                MseeageBean(users = getUserInfoItem, content = content, time = msgTime, newCount = 1, conversationId = conversationId)
            }
        }
        callAdapter.add(0, chat!!)
    }

    private fun updateMessageList(newMessages: List<MseeageBean>, usersMap: Map<String, Users>) {
        if (pageNum == 1) {
            mBinding.rcvList.adapter = helper?.adapter
            if (newMessages.size == usersMap.size) {
                messageAdapterList.clear()
                messageAdapterList.addAll(newMessages)
                callAdapter.notifyDataSetChanged()
            } else {
                if (newMessages.isNotEmpty()) {
                    messageAdapterList.addAll(newMessages)
                    callAdapter.addAll(0, newMessages)
                }

            }
        } else {
            messageAdapterList.addAll(newMessages)
            callAdapter.notifyDataSetChanged()
        }
    }


    override fun onResume() {
        super.onResume()
        pageNum = 1
        Log.e("tag", "onResume")
        refreshData()
    }

    var helper: QuickAdapterHelper? = null
    private fun initAdapter() {

        mBinding.rcvList.setVerticalLayoutManager()
        helper = QuickAdapterHelper.Builder(callAdapter).build()
        helper?.addBeforeAdapter(HeaderAdapter())
        mBinding.rcvList.adapter = helper?.adapter
        callAdapter.submitList(messageAdapterList)
        callAdapter.itemAnimation = CustomAnimation1()
        callAdapter.animationEnable = true

        val view = View.inflate(requireContext(), com.weme.common.R.layout.layout_empty_state, null)
        val tvEmpty = view.findViewById<TextView>(com.weme.common.R.id.tv_empty)
        tvEmpty.text = getText(com.example.resources.R.string.message_empty_msg)

        val btRefresh = view.findViewById<TextView>(com.weme.common.R.id.btRefresh)
        btRefresh.text = getString(com.example.resources.R.string.message_empty_btn)
        btRefresh.setOnClickListener {
         LiveEventBus.get<Any>(LiveConfig.NEW_HOME_INDEX).post(1) //            mBinding.smartLayout.autoRefresh()
        }
        callAdapter.stateView = view
        callAdapter.setOnDebouncedItemClick { _, _, position ->
            viewLifecycleOwner.lifecycleScope.launch {
                callAdapter.getItem(position)?.newCount = 0
                callAdapter.notifyItemChanged(position)
            }

            callAdapter.getItem(position)?.let { ARouterHelper.navigateToChatActivity(requireContext(), it.users) }
        }
        callAdapter.setOnItemLongClickListener { adapter, _, position ->

            val selectionItems = listOf(
                SelectionItem(getString(com.example.resources.R.string.delete), position, this), // 添加更多的 SelectionItem
            )
            val btndialog = BottomSelectionDialog.newInstance(selectionItems)
            btndialog.show(requireActivity().supportFragmentManager,"")
            true
        }
        mBinding.imCallHistory.setOnFastClickListener {
            ARouterHelper.navigateToActivity(requireContext(), ARouterPaths.HISTORY_ACTIVITY)
        }

        mBinding.refresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                Log.e("tag", "onRefresh")
                pageNum = 1
                refreshData()
                mBinding.refresh.finishRefresh()
                mBinding.refresh.finishLoadMore()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                Log.e("tag", "onLoadMore") //                pageNum += 1
                //                refreshData()
                mBinding.refresh.finishRefresh()
                mBinding.refresh.finishLoadMore()
            }

        })
    }

    private var addChatMessage: ChatMessage? = null
    private fun observeViewModel() {
        ChatClient.getInstance().chatManager().addMessageListener { messages ->
            messages?.forEach { newMessage -> // Check if the conversationId is not in callAdapter.items
                val isNewMessage = callAdapter.items.none { it.conversationId == newMessage.conversationId() }

                if (isNewMessage) {
                    val conversationIds: ArrayList<Long> = arrayListOf()
                    conversationIds.add(newMessage.conversationId().toLong())
                    addChatMessage = newMessage //   GlobalScope.launch(Dispatchers.Main) {
                    viewModel.addMseeageList(GetUserInfoRequest.newBuilder().addAllUids(conversationIds).build()) //   }
                } else {
                    messageAdapterList.forEachIndexed { index, existingMessage ->
                        if (newMessage.conversationId() == existingMessage.conversationId) {
                            GlobalScope.launch(Dispatchers.Main) {
                                callAdapter.items[index].time = newMessage.msgTime
                                callAdapter.items[index].content = getMessageContent(newMessage)
                                callAdapter.items[index].newCount = callAdapter.items[index].newCount + 1
                                val movedItem = messageAdapterList.removeAt(index)
                                messageAdapterList.add(0, movedItem)
                                callAdapter.move(index, 0)
                                callAdapter.notifyItemChanged(index)
                            }

                        }
                    }
                }
            }
        }


    }

    var cursor = ""
    fun refreshData() { //  if (!isProne) {
        getMessageListInfo() //       Log.e("tag","从本地获取聊天列表")
        //        } else {
        //
        //            Log.e("tag","从服务器获取聊天列表")

        //        }


    }


    class HeaderAdapter : BaseSingleItemAdapter<Any, HeaderAdapter.VH>() {

        class VH(view: View) : RecyclerView.ViewHolder(view)

        override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_message_head_view, parent, false)
            return VH(view)
        }

        override fun onBindViewHolder(holder: VH, item: Any?) { // 可以在此绑定数据
        }
    }

    private val callAdapter = object : BaseQuickAdapter<MseeageBean, QuickViewHolder>() {
        override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: MseeageBean?) {
            item?.apply {
                holder.apply {
                    setText(R.id.tvName, setNameAge(getString(com.example.resources.R.string.user_info_format, users.nickname, users.age)))
                    setText(R.id.tvContent, content)
                    val rimHead = getView<RoundedImageView>(R.id.rim_head)
                    rimHead.loadImage(users.headPic)
                    setText(R.id.tvTime, TimeUtils.convertTimestampToRelativeTime(time))
                    setGone(R.id.imNew, newCount == 0)
                    val country = getCountryBean(users.countryCode)

                    country?.let {
                        getView<SmoothImageView>(R.id.imFlag).loadImage(it.countryFlag)
                    }
                    val vCircle = holder.getView<View>(R.id.vCircle)
                    when (users.onlineStatus) {
                        1 -> {
                            vCircle.visible()
                            vCircle.setBackgroundResource(com.example.resources.R.drawable.online_dot)
                        }
                        2 -> {
                            vCircle.visible()
                            vCircle.setBackgroundResource(com.example.resources.R.drawable.busy_dot)
                        }
                        else -> {
                            vCircle.gone()

                        }
                    }
                }
            }


        }

        override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
            return QuickViewHolder(R.layout.item_call_home, parent)
        }


    }

    private fun getMessageListInfo() { //那聊天记录 按照时间排序
        try {
            val sortedConversations = AgoraClient.getInstance().getMessageList().values.toList().sortedByDescending { it.lastMessage.msgTime }
            if (sortedConversations.isEmpty()) {
                ChatClient.getInstance().chatManager().asyncFetchConversationsFromServer(50, cursor, object : ValueCallBack<CursorResult<Conversation>> {
                    override fun onSuccess(value: CursorResult<Conversation>?) {
                        value?.let {
                            if (it.data.size != 0) {
                                cursor = it.cursor
                                val conversationIds: List<Long> = it.data.filterNotNull().map { it.conversationId().toLong() }
                                viewModel.getMseeageList(GetUserInfoRequest.newBuilder().addAllUids(conversationIds).build())
                            } else if (cursor == "") {
                                mBinding.rcvList.post {
                                    callAdapter.isStateViewEnable = true
                                }

                            }

                        }
                    }

                    // 获取会话失败处理逻辑。
                    override fun onError(error: Int, errorMsg: String) {}
                })
            } else { //拿到顺序的id
                val conversationIds: List<Long> = sortedConversations.map { it.conversationId().toLong() } //请求服务器
                viewModel.getMseeageList(GetUserInfoRequest.newBuilder().addAllUids(conversationIds).build())
            }
        } catch (e: Exception) {

        }


    }

    override fun clickListener() {
    }



    override fun getViewModel(): Class<MessageViewMode> = MessageViewMode::class.java
    override fun onTitleClicked(position: Int) {
        ChatClient.getInstance().chatManager().deleteConversation(callAdapter.getItem(position)?.conversationId, true)

        ChatClient.getInstance().chatManager().deleteConversationFromServer(callAdapter.getItem(position)?.conversationId, Conversation.ConversationType.Chat, true, object : CallBack {
            override fun onSuccess() {

            }

            override fun onError(code: Int, error: String) {}
        })
        callAdapter.removeAt(position)
    }
}